/**
 * Copyright © 2022 易久批信息技术有限公司. All rights reserved.
 */
package com.dysm.multithread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 可重入锁控制三个线程按顺序输出ABC
 * @author xiay
 * @since 2022/3/5 8:39 下午
 */
public class ABCReentrantPrintTest {

    private static Lock lock = new ReentrantLock();

    private static int state = 0;

    public static void main(String[] args) {

        new A().start();
        new B().start();
        new C().start();

    }

    static class A extends Thread {

        @Override
        public void run() {
            for (int i = 0; i < 10;) {
                lock.lock();
                if (state % 3 == 0) {
                    state ++;
                    System.out.print("A");
                    i ++;
                }
                lock.unlock();
            }

        }
    }
    static class B extends Thread {

        @Override
        public void run() {
            for (int i = 0; i < 10;) {
                lock.lock();
                if (state % 3 == 1) {
                    state ++;
                    System.out.print("B");
                    i ++;
                }
                lock.unlock();
            }

        }
    }
    static class C extends Thread {

        @Override
        public void run() {
            for (int i = 0; i < 10;) {
                lock.lock();
                if (state % 3 == 2) {
                    state ++;
                    System.out.println("C");
                    i ++;
                }
                lock.unlock();
            }

        }
    }
}
